package com.gitee.feizns.web.boot.validate;

import com.gitee.feizns.web.boot.utils.AppUtilsAutoConfiguration;
import com.gitee.feizns.web.utils.AppUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;

import java.util.Collection;

/**
 * @author feizns
 * @since 2019/7/19
 */
@AutoConfigureAfter(AppUtilsAutoConfiguration.class)
@Configuration
@EnableConfigurationProperties(ValidateProperties.class)
public class ValidateAutoConfiguration {

    @Autowired
    private ValidateProperties properties;

    private boolean initialized = false;

    @EventListener
    public void init(ContextRefreshedEvent event) {
        if ( initialized == false ) {
            Collection<ValidateConfigurer> configurers = AppUtils.getBeansOfType(ValidateConfigurer.class);

            for (ValidateConfigurer configurer : configurers) {
                configurer.extendsValidateErrorMapping(properties.getValidateErrorMapping());
                configurer.extendsEntityErrorMapping(properties.getValidatorEntityErrorMapping());
            }

            initialized = true;
        }
    }

}
